import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

def send_dingtalk(webhook: str,
                  secret: str = None,
                  text: str = '',
                  at_mobiles: list = None,
                  at_all: bool = False):
    """
    向钉钉群机器人发送文本消息
    :param webhook: 机器人 Webhook 地址（形如 https://oapi.dingtalk.com/robot/send?access_token=XXX）
    :param secret:  如果机器人启用了“加签”，需要传入 secret；否则保持 None
    :param text:    要发送的文本内容
    :param at_mobiles: 需要 @ 的手机号列表，如 ['13800000000']
    :param at_all: 是否 @ 所有人
    :return: dict   钉钉接口返回的 JSON
    """
    at_mobiles = at_mobiles or []

    # 1. 处理加签
    if secret:
        timestamp = str(round(time.time() * 1000))
        sign_str = f'{timestamp}\n{secret}'
        sign = hmac.new(
            secret.encode('utf-8'),
            sign_str.encode('utf-8'),
            digestmod=hashlib.sha256
        ).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(sign))
        webhook += f'&timestamp={timestamp}&sign={sign}'

    # 2. 组装消息体
    data = {
        "msgtype": "text",
        "text": {"content": text},
        "at": {
            "atMobiles": at_mobiles,
            "isAtAll": at_all
        }
    }

    # 3. 发送
    resp = requests.post(
        url=webhook,
        data=json.dumps(data),
        headers={'Content-Type': 'application/json'}
    )
    resp.raise_for_status()
    return resp.json()


def send_msg_2_ding(msg):
    # 把下面两行换成你的真实地址与密钥
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=21b8a2f7e8f275d4954d6bac104a3f6752f37f09ce30c9904f150830b5b1cadb'
    secret_key = 'SEC0ba66b2cbd7e7fcf332e6ca74103631d82110e13c2e3b63e09a0a0ec669490ed'  # 如果没启用加签，保持 None

    res = send_dingtalk(
        webhook=webhook_url,
        secret=secret_key,
        text= msg,
        at_mobiles=['13800000000'],
        at_all=False
    )

# ------------------ DEMO ------------------
if __name__ == '__main__':
    # 把下面两行换成你的真实地址与密钥
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=21b8a2f7e8f275d4954d6bac104a3f6752f37f09ce30c9904f150830b5b1cadb'
    secret_key  = 'SEC0ba66b2cbd7e7fcf332e6ca74103631d82110e13c2e3b63e09a0a0ec669490ed'  # 如果没启用加签，保持 None

    res = send_dingtalk(
        webhook=webhook_url,
        secret=secret_key,
        text='Hello from Python 🎉',
        at_mobiles=['13800000000'],
        at_all=False
    )
    print(res)